
package pl.genapp.stocksense.libraries;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;

public class FacebookHelper {
	
	public static final int FACEBOOK_RESPONSE = 32665;
	public static final String SHARED_PREFERENCE_FACEBOOK = "facebook";
	public static final String PREF_KEY_ACCESS_TOKEN = "access_token";
	public static final String PREF_KEY_EXPIRES_IN = "expires_in";
	private static final String APP_ID = "313255202112289";
	private Activity activity;
	private Facebook facebook;
	
	public class CustomFbDialogListener implements Facebook.DialogListener {
		
		public void onComplete(Bundle values) {
			
		}
		
		public void onFacebookError(FacebookError e) {
			Toast.makeText(activity, "There was an error on fb side", Toast.LENGTH_SHORT).show();
		}
		
		public void onError(DialogError e) {
			Toast.makeText(activity, "There was an erro", Toast.LENGTH_SHORT).show();
		}
		
		public void onCancel() {
			
		}
		
	}
	
	public FacebookHelper(Activity activity) {
		this.activity = activity;
		facebook = new Facebook(APP_ID);
	}
	
	public void logIn(CustomFbDialogListener fbListener) {
		
		facebook.authorize(activity, new String[] { "publish_stream" }, fbListener);
		
	}
	
	public boolean isLogged() {
		Log.d("stocksense", "isLogged!");
		
		SharedPreferences preferences = activity.getSharedPreferences(SHARED_PREFERENCE_FACEBOOK, 0);
		
		String accessToken = preferences.getString(PREF_KEY_ACCESS_TOKEN, null);
		String expireIn = preferences.getString(PREF_KEY_EXPIRES_IN, null);
		
		if (accessToken != null && expireIn != null) {
			
			long current = System.currentTimeMillis() / 1000L;
			if (Long.parseLong(expireIn) > current)
				return true;
			else
				return false;
			
		} else
			return false;
		
	}
	
	public void saveResultToSP(Intent data) {
		Log.d("stocksense", "saveResultToSP");
		if (data != null) {
			
			SharedPreferences preferences = activity.getSharedPreferences(SHARED_PREFERENCE_FACEBOOK, 0);
			SharedPreferences.Editor editor = preferences.edit();
			String accessToken = data.getStringExtra("access_token");
			if (accessToken != null) editor.putString(PREF_KEY_ACCESS_TOKEN, accessToken);
			Log.d("stocksense", "saveResultToSP1");
			String expiresIn = data.getStringExtra("expires_in");
			if (expiresIn != null) {
				long current = System.currentTimeMillis() / 1000L;
				Log.d("stocksense", "saveResultToSP2");
				Long fbExpires = Long.parseLong(expiresIn);
				fbExpires += current;
				
				editor.putString(PREF_KEY_EXPIRES_IN, fbExpires.toString());
				
				Toast.makeText(activity, "Facebook connect - success!", Toast.LENGTH_SHORT).show();
			}
			
			editor.commit();
		} else
			Log.d("stocksense", "intent data fb empty!");
	}
	
	public void shareOnFacebook(byte[] image, String text) {
		
		final Bundle postParams = new Bundle();
		Log.d("stocksense", "shareOnFacebook");
		postParams.putString("name", text);
		postParams.putByteArray("picture", image);
		postParams.putString("access_token", getAccessToken());
		
		new AsyncTask<Void, Void, String>() {
			
			protected String doInBackground(Void[] params) {
				
				try {
					
					String response = facebook.request("/me/photos", postParams, "POST");
					Log.d("stocksense", response);
					return response;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				return null;
			};
			
			protected void onPostExecute(String result) {
				
				// sprawdzamy czy dodalo
				JSONObject json;
				try {
					json = new JSONObject(result);
					if (!json.isNull("post_id")) {
						Toast.makeText(activity, "Facebook share success!", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(activity, "ERROR ON FB SIDE!!", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			};
			
		}.execute();
		
	}
	
	public String getAccessToken() {
		
		SharedPreferences preferences = activity.getSharedPreferences(SHARED_PREFERENCE_FACEBOOK, 0);
		String accessToken = preferences.getString(PREF_KEY_ACCESS_TOKEN, null);
		
		return accessToken;
		
	}
	
}
